package com.lin.cloud.disk.common.exception;

import com.lin.cloud.disk.common.enums.EResponseCode;
import com.lin.cloud.disk.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;

/**
 * 全局异常处理
 *
 * @author ljc
 * @date 2020/12/10 14:07
 */
@Slf4j
@CrossOrigin
@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_PARAM_ERROR);
        result.setSuccess(false);
        result.setMessage(e.getMessage());
        if (e.getCause() instanceof BusinessException) {
            BusinessException exception = (BusinessException) e.getCause();
            result.setCode(exception.getCode());
            result.setMessage(exception.getDescription());
        }
        return result;
    }


    /**
     * 业务异常处理(指自定义的业务异常提示)
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_BUSINESS_ERROR);
        result.setSuccess(false);
        if (StringUtils.isNotBlank(e.getCode())) {
            result.setCode(e.getCode());
        }
        if (StringUtils.isNotBlank(e.getDescription())) {
            result.setMessage(e.getDescription());
        }
        return result;
    }


    /**
     * 数据合法性校验异常处理,检验对象加上@Validated
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_PARAM_ERROR);
        result.setSuccess(false);
        String msg = null;
        if (null != e.getBindingResult().getFieldError()) {
            msg = e.getBindingResult().getFieldError().getDefaultMessage();
        }
        if (StringUtils.isBlank(msg)) {
            if (null != e.getBindingResult().getGlobalError()) {
                msg = e.getBindingResult().getGlobalError().getDefaultMessage();
            }
        }
        result.setMessage(msg);
        return result;
    }

    /**
     * 数据校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        log.error("数据校验异常", e);
        Result result = Result.fail(EResponseCode.SYSTEM_PARAM_ERROR);
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String msg = fieldError.getDefaultMessage();
        result.setMessage(msg);
        return result;
    }

    /**
     * 请求方法不存在/不可用异常处理(一般指请求方式不对,如get post)
     *
     * @param e
     * @return
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class})
    public Result handleHttpRequestMethodNotSupportedException(Exception e) {
        log.error("请求方法异常：", e);
        Result result = null;
        if (e instanceof HttpRequestMethodNotSupportedException) {
            result = new Result(EResponseCode.SYSTEM_METHOD_NOT_ALLOWED);
        } else {
            result = new Result(EResponseCode.SYSTEM_REQUEST_FAILE);
        }
        result.setSuccess(false);
        return result;
    }

    @ExceptionHandler(value = org.apache.shiro.authc.AuthenticationException.class)
    @ResponseBody
    public Result defaultAuthenticationExceptionHandler(Exception e) throws Exception {
        log.error("登录异常捕获：", e);
        Result result = Result.fail(EResponseCode.LOGON_FAIL);
        return result;
    }

    /**
     * 系统异常处理，比如：404,500
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(Exception e) throws Exception {
        log.error("全局异常捕获：", e);
        Result result = Result.fail(EResponseCode.SYSTEM_BUSY_ERROR);
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            result = Result.fail(EResponseCode.NOT_FOUND);
        }
        return result;
    }

}
